import webbrowser

import webview
from flask import render_template, jsonify, request, json

from core.cpucheck import CpuCheck
from core.cpuregist import CpuRegist
from core.login import Login
from core.storeinfo import StoreInfo
from core.users import Users
from core.vip import Vip
from server import app
from tools.gethardware import GethardWare
from webapp import extend
from tools import weather, md5, OperationError
import core.init.initconfig.tableConfig as tableConfig
import core.order as order
from core.data_update import DataUpdate
# from core.init.initsysparam import initsysparam
from core.init.initinfo import InitInfo


@app.after_request
def add_header(response):
    response.headers['Cache-Control'] = 'no-store'
    return response


@app.route("/")
def landing():
    """
    Render indexold.html. Initialization is performed asynchronously in initialize() function
    """
    return render_template("index.html")


@app.route("/init")
def initialize():
    """
    Perform heavy-lifting initialization asynchronously.
    :return:
    """
    can_start = extend.initialize()

    if can_start:
        response = {
            "status": "ok",
        }
    else:
        response = {
            "status": "error"
        }

    return jsonify(response)


@app.route("/choose/path")
def choose_path():
    """
    Invoke a folder selection dialog here
    :return:
    """
    dirs = webview.create_file_dialog(webview.FOLDER_DIALOG)
    if dirs and len(dirs) > 0:
        directory = dirs[0]
        if isinstance(directory, bytes):
            directory = directory.decode("utf-8")

        response = {"status": "ok", "directory": directory}
    else:
        response = {"status": "cancel"}

    return jsonify(response)


@app.route("/fullscreen")
def fullscreen():
    webview.toggle_fullscreen()
    return jsonify({})


@app.route("/open-url", methods=["POST"])
def open_url():
    url = request.json["url"]
    webbrowser.open_new_tab(url)

    return jsonify({})


@app.route("/do/stuff")
def do_stuff():
    result = extend.do_stuff()

    if result:
        response = {"status": "ok", "result": result}
    else:
        response = {"status": "error"}

    return jsonify(response)


@app.route("/baidu", methods=["POST"])
def do_baidu():
    webview.load_url("http://www.baidu.com")
    return jsonify({})


# 获取天气的路由
@app.route("/tools/weather", methods=["POST"])
def get_weather():
    response = weather.getweather()
    return jsonify(response)


# 获取零售单表格的表头
# @app.route("/api/retailcolumns", methods=["POST"])
# def get_retailcolumns():
#     response = tableConfig.get_tablecolumns('retailProducts')
#     return jsonify(response)


# # 商品录入（款号查询）
# @app.route("/api/order", methods=["POST"])
# def get_searchproducts():
#     # init_data=DataUpdate()
#     # response=init_data.Upgrade()
#     order_obj = order.Retail()
#     param = request.get_json(True)
#     response = order_obj.SearchProducts(param)
#     return jsonify(response)


# # 商品详细信息里的图片查询接口
# @app.route("/api/searchpropic", methods=["POST"])
# def get_productpic():
#     order_obj = order.Retail()
#     param = request.get_json(True)
#     pro = param["product"]
#     response = order_obj.get_productpic(pro)
#     return jsonify(response)


# # 商品详细信息里的图片查询接口
# @app.route("/api/deletepros", methods=["POST"])
# def deletepros():
#     order_obj = order.Retail()
#     param = request.get_json(True)
#     pro = param["lineno"]
#     response = order_obj.delete_pro(pro)
#     return jsonify(response)


#
@app.route("/api/pos/cpuInit", methods=["POST", "GET"])
def init_data():

    try:
        init = InitInfo()
        res = init.init_info()
        if not res:
            res = {}
            res["code"] = 0
            res["message"] = "初始化完成"
    except Exception as e:
        res = {}
        res["code"] = -1
        res["message"] = e.__str__()

    return jsonify(res)


